package com.lagou.handler;

import com.lagou.common.constant.Constants;
import com.lagou.service.UserServiceImpl;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;

import java.io.IOException;
import java.net.SocketAddress;

public class UserServerHandler extends ChannelInboundHandlerAdapter {



    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        Channel channel = ctx.channel();
        //InetSocketAddress insocket = (InetSocketAddress) ctx.channel().remoteAddress();
        SocketAddress socketAddress = channel.localAddress();
        //String serverIp = insocket.getAddress().getHostAddress();

        //String serverPort = String.valueOf(insocket.getPort());
        System.out.println("被调用服务方的地址为：" + socketAddress);
        long startTime = System.currentTimeMillis();
        System.out.println("服务端开始执行的时间为：" + startTime);

        // 判断是否符合约定，符合则调用本地方法，返回数据
        // msg:  UserService#sayHello#are you ok?
        if(msg.toString().startsWith("UserService")){
            UserServiceImpl userService = new UserServiceImpl();
            String result = userService.sayHello(msg.toString().substring(msg.toString().lastIndexOf("#") + 1));
            ctx.writeAndFlush(result);
            doCalcTime(startTime,socketAddress);
        }
    }

    private void doCalcTime(long startTime,SocketAddress socketAddress) throws IOException, KeeperException, InterruptedException {
        ZooKeeper zk = new ZooKeeper(Constants.REGISTRY_ADDRESS, Constants.ZK_SESSION_TIMEOUT, new Watcher() {
            @Override
            public void process(WatchedEvent event) {
            }
        });
        long endTime = System.currentTimeMillis();
        long costTime = endTime - startTime;
        System.out.println("服务端结束执行的时间为：" + endTime + ";执行花费时间为：" + costTime);
        String data = socketAddress + ";" + endTime + ";" + costTime;
        System.out.println("=====：" + new String(zk.getData(Constants.ZK_DATA_PATH, false, null)));
        zk.setData(Constants.ZK_DATA_PATH, data.getBytes(),-1);
        System.out.println("修改后的值：" + new String(zk.getData(Constants.ZK_DATA_PATH, false, null)));
    }
}
